package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"time"
	"zy31/api/pkg"

	"zy31/api/internal/svc"
	"zy31/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	file, header, err := req.FormFile("img")
	if header.Size > 200*1024 {
		return &types.Response{
			Msg:  "文件大小不能超过200kb",
			Data: nil,
			Code: 500,
		}, nil
	}
	ext := filepath.Ext(header.Filename)
	if ext != ".png" && ext != ".jpg" {
		return &types.Response{
			Msg:  "上传的图片格式只能为 png、jpg",
			Data: nil,
			Code: 500,
		}, nil
	}
	fileName := time.Now().Format("20060102150405") + ext
	upload, err := pkg.Upload(file, header, fileName)
	if err != nil {
		return &types.Response{
			Msg:  "上次失败",
			Data: nil,
			Code: 500,
		}, nil
	}
	return &types.Response{
		Msg:  "上次成功",
		Data: upload,
		Code: 200,
	}, nil
}
